import time
import subprocess

from board import *
import busio
from PIL import Image, ImageDraw, ImageFont
import adafruit_ssd1306

i2c = busio.I2C(I2C2_SCL, I2C2_SDA)
disp = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c)

#清屏
disp.fill(0)
disp.show()

width = disp.width
height = disp.height
#单色位图
image = Image.new("1", (width, height))

#定义绘图对象
draw = ImageDraw.Draw(image)

#绘制一个黑色填充的矩形以清屏
draw.rectangle((0, 0, width, height), outline=0, fill=0)

#定义一些常量
padding = -2
top = padding
bottom = height - padding
x = 0

#定义字体
font = ImageFont.load_default()

while True:
    draw.rectangle((0, 0, width, height), outline=0, fill=0)

    # 调用命令显示IP、CPU、内存、存储等信息
    cmd = "hostname -I | cut -d' ' -f1"
    IP = subprocess.check_output(cmd, shell=True).decode("utf-8")
    cmd = 'cut -f 1 -d " " /proc/loadavg'
    CPU = subprocess.check_output(cmd, shell=True).decode("utf-8")
    cmd = "free -m | awk 'NR==2{printf \"Mem: %s/%s MB  %.2f%%\", $3,$2,$3*100/$2 }'"
    MemUsage = subprocess.check_output(cmd, shell=True).decode("utf-8")
    cmd = 'df -h | awk \'$NF=="/"{printf "Disk: %d/%d GB  %s", $3,$2,$5}\''
    Disk = subprocess.check_output(cmd, shell=True).decode("utf-8")

    draw.text((x, top + 0), "IP: " + IP, font=font, fill=255)
    draw.text((x, top + 8), "CPU: " + CPU, font=font, fill=255)
    draw.text((x, top + 16), MemUsage, font=font, fill=255)
    draw.text((x, top + 25), Disk, font=font, fill=255)

    # 显示信息
    disp.image(image)
    disp.show()
    time.sleep(0.1)
